<!DOCTYPE HTML>

<head>
    <title>第二第四题</title>

    <link href="ol/ol.css" rel="stylesheet" type="text/css" />
    <script src="./js/ol-debug.js" type="text/javascript"></script>
    <script src="./js/jquery-1.11.2.min.js" type="text/javascript"></script>
    <script src="./js/zondyClient.js" type="text/javascript"></script>


    <style type="text/css">
        .map {
            width: 100%;
            height: 95%;
            position: absolute;
        }

        div,
        ul,
        li,
        iframe,
        p,
        img {
            border: none;
            padding: 0;
            margin: 0;
            font-size: 14px;
            font-family: "微软雅黑";
        }


        /*图层控件层样式设计*/
        .layerControl {
            position: absolute;
            bottom: 5px;
            min-width: 200px;
            max-height: 230px;
            right: 0px;
            top: 50px;
            /*在地图容器中的层，要设置z-index的值让其显示在地图上层*/
            z-index: 2001;
            color: #ffffff;
            background-color: #4c4e5a;
            /*边缘的宽度*/
            border-width: 10px;
            /*圆角的大小 */
            border-radius: 10px;
            /*边框颜色*/
            border-color: #000 #000 #000 #000;
        }

        .layerControl .title {
            font-weight: bold;
            font-size: 15px;
            margin: 10px;
        }

        .layerTree li {
            list-style: none;
            margin: 5px 10px;
        }


        /*功能栏设计*/
        .menuCon {
            position: absolute;
            bottom: 5px;
            min-width: 200px;
            max-height: 100px;
            left: 200px;
            top: 0px;
            z-index: 2001;
            color: #ffffff;
            background-color: #4c4e5a;
            /*边缘的宽度*/
            border-width: 10px;
            /*圆角的大小 */
            border-radius: 10px;
            /*边框颜色*/
            border-color: #000 #000 #000 #000;
        }

        .menuCon .title {
            font-weight: bold;
            font-size: 15px;
            margin: 10px;
        }

        .menuTree li {
            list-style: none;
            margin: 5px 10px;
        }

        /* 鼠标位置控件层样式设置 */
        #mouse-position {
            float: left;
            position: absolute;
            bottom: 5px;
            width: 330px;
            height: 20px;
            /*在地图容器中的层，要设置z-index的值让其显示在地图上层*/
            z-index: 2000;
        }

        .marker {
            width: 20px;
            height: 20px;
            border: 1px solid #088;
            border-radius: 10px;
            background-color: #0FF;
            opacity: 0.5;
        }

        .address {
            text-decoration: none;
            color: #aa3300;
            font-size: 14px;
            font-weight: bold;
            text-shadow: black 0.1em 0.1em 0.2em;
        }
    </style>
</head>

<body>
    <div id="map" class="map">
        <div id="mouse-position"></div>
        <div id="layerControl" class="layerControl">
            <div class="title"><label>图层列表</label></div>
            <ul id="layerTree" class="layerTree"></ul>
        </div>
        <div id="menu" class="menuCon">
            <div class="title" align="center">
                <label>功能栏</label>
            </div>
            <ul id="menuTree" class="menuTree">
                <select id="function_input" style="margin: 10px;" onchange="fun_select()">
                    <option value="option0">请选择</option>
                    <option value="option1">图文标注</option>
                    <option value="option2">地图绘制</option>
                    <option value="option23">样式编辑</option>
                </select>
            </ul>
        </div>

        <div id="label" style="display: none;" class="ol.popup">
            <div id="marker" class="marker" title="Marker">
                
                <a class="address" id="address" target="_blank" href="http://www.openlayers.org/">标注点</a>
            </div>
        </div>
    </div>
    
    <script type="text/javascript">
        var proj;
        //图层定义
        var tian_di_tu_road_layer;
        var tian_di_tu_annotation;
        var tian_di_tu_ter_layer;
        var tian_di_tu_satellite_layer;
        var GUANGXI_Layer;

        //新建矢量标注的数据源
        var vectorMarkSource = new ol.source.Vector({
            features: []
        });
        var vectorMarkLayer = new ol.layer.Vector({
            source: vectorMarkSource,
            name: "矢量标注图层"
        });


        //绘制对象
        var draw;
        //矢量图层 用于绘制要素
        var vectorDrawSource = new ol.source.Vector({
            wrapX: false
        })
        var vectorDrawLayer = new ol.layer.Vector({
            name: "绘制图层",
            source: vectorDrawSource,
            style: new ol.style.Style({
                fill: new ol.style.Fill({
                    color: 'rgba(255, 255, 255, 0.2)'
                }),
                stroke: new ol.style.Stroke({
                    color: '#ffcc33',
                    width: 2
                }),
                image: new ol.style.Circle({
                    radius: 7,
                    fill: new ol.style.Fill({
                        color: '#ffcc33'
                    })
                })
            })
        });



        //map中的图层数组
        var layer = new Array();
        //map中图层的名称数组
        var layerName = new Array();
        //map图层的可见属性数组
        var layerVisibility = new Array();


        /**
         * 创建矢量标注样式函数，设置image图标为ol.style.Icon
         * @param{ol.Feature} feature要素
         * return ol.style.Style 返回样式
         */
        var createLabelStyle = function (feature) {
            return new ol.style.Style({
                image: new ol.style.Icon(
                    /** @type {ol.style.IconOptions} */
                    ({
                        anchor: [0.5, 60],
                        anchorOrigin: 'top-right',
                        anchorXUnits: 'fraction',
                        anchorYUnits: 'pixels',
                        offsetOrigin: 'top-right',
                        // offset:[0,10],
                        //图标缩放比例
                        // scale:0.5,
                        //透明度
                        opacity: 0.75,
                        //图标的url
                        src: './images/vetor.png'
                    })
                ),
                text: new ol.style.Text({
                    //位置
                    textAlign: 'center',
                    //基准线
                    textBaseline: 'middle',
                    //文字样式
                    font: 'normal 14px 微软雅黑',
                    //文本内容
                    text: feature.get('name'),
                    //文本填充样式
                    fill: new ol.style.Fill({ color: '#aa330' }),
                    stroke: new ol.style.Stroke({ color: '#ffcc33', width: 2 })
                })
            });
        }



        /**
         * 加载图层列表的数据
         * @param{ol.Map} map 地图对象
         * @param{string} id 图层列表的容器ID
        */
        function loadLayersControl(map, id) {
            //图层目录容器
            var treeContent = document.getElementById(id);
            //获取map的所有图层
            var layers = map.getLayers();
            for (var i = 0; i < layers.getLength(); i++) {
                //每个图层及图层的名称、可见属性分别存到数组中
                layer[i] = layers.item(i);
                layerName[i] = layer[i].get('name');
                layerVisibility[i] = layer[i].getVisible();

                //新增li元素 承载图层项
                var elementLi = document.createElement('li');
                //添加子节点
                treeContent.appendChild(elementLi);

                //新增复选框元素 控制对应图层 添加到li元素节点中
                var elementInputName = document.createElement('input');
                elementInputName.type = "checkbox";
                elementInputName.name = "layers";
                elementLi.appendChild(elementInputName);

                //创建label元素 显示图层的名称
                var elementLabel = document.createElement('label');
                elementLabel.className = "layer";

                //设置图层的名称以及图层的默认显示状态
                setInnerText(elementLabel, layerName[i]);
                elementLi.appendChild(elementLabel);
                if (layerVisibility[i]) {
                    elementInputName.checked = true;
                }
                //为checkbox添加变更事件
                addChangeVisibleEvent(elementInputName, layer[i]);

                //添加图层的透明度控制
                var elementInputOpacity = document.createElement("INPUT");
                elementInputOpacity.setAttribute("type", "range");
                elementInputOpacity.min = 0;
                elementInputOpacity.max = 1;
                elementInputOpacity.step = 0.01;
                elementLi.appendChild(elementInputOpacity);
                //为透明度控制添加绑定事件
                addChangeOpacityEvent(elementInputOpacity, layer[i]);

            }
        }

        /**
         * range元素的绑定事件
         * @param{input} element range元素
         * @param{ol.map.Layer} layer 图层对象
         */
        function addChangeOpacityEvent(element, layer) {
            element.oninput = function () {
                layer.setOpacity(parseFloat(element.value));

            }

        }



        /**
         * checkbox元素绑定的变更事件
         * @param {input} element checkbox元素
         * @param {ol.map.Layer} layer 图层对象
        */
        function addChangeVisibleEvent(element, layer) {
            element.onclick = function () {
                if (element.checked) {
                    layer.setVisible(true);
                }
                else {
                    layer.setVisible(false);
                }
            };
        }
        /**
         * 动态显示元素文本内容
         * @param {label} element label元素
         * @param {layerName} Array 图层名称
         */
        function setInnerText(element, text) {
            if (typeof element.textContent == "string") {
                element.textContent = text;
            }
            else {
                element.innerText = text;
            }
        };

        proj = ol.proj.fromLonLat([107.41, 37.82]);



        var map = new ol.Map({
            layers: [

            ],

            target: 'map',
            view: new ol.View({
                center: [114.3, 30.6],
                zoom: 5,
                maxZoom: 18,
                minZoom: 3,
                projection: "EPSG:4326",
            }),
            controls: ol.control.defaults().extend([
                new ol.control.MousePosition({
                    target: document.getElementById('mouse-position')
                })
            ])

        });
        tian_di_tu_road_layer = new ol.layer.Tile({
            name: "天地图路网",
            source: new ol.source.XYZ({
                url: "http://t4.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=42dca576db031641be0524ee977ddd04"
            })
        });
        map.addLayer(tian_di_tu_road_layer);


        tian_di_tu_ter_layer = new ol.layer.Tile({
            name: "天地图地形图",
            source: new ol.source.XYZ({
                url: "http://t3.tianditu.com/DataServer?T=ter_w&x={x}&y={y}&l={z}&tk=42dca576db031641be0524ee977ddd04"
            })
        })
        map.addLayer(tian_di_tu_ter_layer);

        tian_di_tu_satellite_layer = new ol.layer.Tile({
            name: "天地图卫星影像",
            source: new ol.source.XYZ({
                url: "http://t3.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=42dca576db031641be0524ee977ddd04"
            })
        })
        map.addLayer(tian_di_tu_satellite_layer);

        tian_di_tu_annotation = new ol.layer.Tile({
            name: "天地图文字注记",
            source: new ol.source.XYZ({
                url: "http://t3.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=42dca576db031641be0524ee977ddd04"
            })
        });
        map.addLayer(tian_di_tu_annotation);


        GUANGXI_Layer = new Zondy.Map.Doc("广西行政地图", "GUANGXI", {
            ip: "localhost",
            port: "6163",
            isBaseLayer: true
        });
        map.addLayer(GUANGXI_Layer);


        map.addLayer(vectorMarkLayer);
        map.addLayer(vectorDrawLayer);
        loadLayersControl(map, "layerTree");


        function fun_select() {
            var selected_fun = document.getElementById("function_input");
            var funContent = document.getElementById("menuTree");
            if (selected_fun.value == "option0") {
                if (funContent.hasChildNodes()) {
                    for (let i = 1; i < funContent.children.length; i++) {
                        funContent.removeChild(funContent.children[i]);
                    }
                }

            }
            else if (selected_fun.value == "option1") {

                if (funContent.hasChildNodes()) {
                    for (let i = 1; i < funContent.children.length; i++) {
                        funContent.removeChild(funContent.children[i]);
                    }
                }
                var mark_select = document.createElement("select");
                mark_select.id = "mark_select";
                mark_select.add(new Option("样式点1", "mark1"));
                mark_select.add(new Option("样式点2", "mark2"));
                funContent.appendChild(mark_select);

            }
            else if (selected_fun.value == "option2") {
                if (funContent.hasChildNodes()) {
                    for (let i = 1; i < funContent.children.length; i++) {
                        funContent.removeChild(funContent.children[i]);
                    }
                }

                /*if (window.addEventListener) { // Mozilla, Netscape, Firefox
                    mark_select.addEventListener('change', Change(), false);
                } else { // IE
                    mark_select.attachEvent('onchange', Change());
                }*/

                funContent.appendChild(draw_select);
                draw_select.style.display = "";

                addInteraction();

            }
            else {
                alert("样式编辑");
            }
        }

        var draw_select = document.createElement("select");
        draw_select.id = "draw_select";
        draw_select.style.display = "none";
        //draw_select.style.display = "";
        draw_select.add(new Option("无", "none"));
        draw_select.add(new Option("绘制点", "Point"));
        draw_select.add(new Option("绘制线", "LineString"));
        draw_select.add(new Option("绘制圆", "Circle"));
        draw_select.add(new Option("多边形", "Polygon"));
        draw_select.add(new Option("正方形", "Square"));
        draw_select.add(new Option("矩形", "Box"));
        draw_select.add(new Option("画图", "drawgraph"));
        draw_select.options[1].setAttribute("selected", "true");
        draw_select.onchange = function (e) {
            //移除绘制图形
            map.removeInteraction(draw);
            //添加交互绘制功能控件
            addInteraction();
        };


        /**
         * 地图的点击事件
         * @param{click, e}
         * 
         */
        map.on('click', function (evt) {
            //var type = $("input[name='label']:checked").val();
            //鼠标单击点坐标
            var point = evt.coordinate;

            //alert(point);
            var selected_fun = document.getElementById("function_input");
            var mark_select = document.getElementById("mark_select");
            //判断此时功能栏要求的事件
            if (selected_fun.value == "option0") {
                alert("鼠标位置:"+point);
             }
            //标注事件
            else if (selected_fun.value == "option1") {
                if (mark_select.value == "mark1") {

                    //添加一个新的标注（矢量要素）
                    addVectorLabel(point);
                }
                else {

                    //添加新的图文标注（overlay标注）
                    addOverlayLabel(point);
                }

            }
            else if (selected_fun.value == "option2") {



            }

        }

        );


        /**
         * 绑定addInteraction的事件  用来交互绘画对象的判断 以及监听当前的绘画
         * @param{ select.value } element元素select的value值
         */

        function addInteraction() {


            var select = document.getElementById("draw_select");

            var value = select.value;
            console.log(value);

            if (value !== 'none') {
                console.log("value !== 'none'")
                if (vectorDrawSource == null) {
                    vectorDrawSource = new ol.source.Vector({ wrapX: false });
                    //添加绘制层数据源
                    vectorDrawLayer.setSource(vectorDrawSource);
                }
                var geometryFunction, maxPoints;
                if (value === 'Square') {
                    value = 'Circle';
                    //利用ol的交互绘画方法绘制正方形
                    geometryFunction = ol.interaction.Draw.createRegularPolygon(4);
                }
                else if (value === 'Box') {
                    value = 'LineString';
                    maxPoints = 2;
                    geometryFunction = function (coordinates, geometry) {
                        if (!geometry) {
                            geometry = new ol.geom.Polygon(null);
                        }
                        var start = coordinates[0];
                        var end = coordinates[1];
                        geometry.setCoordinates([
                            [start, [start[0], end[1]], end, [end[0], start[1]], start]
                        ]);
                        return geometry;
                    };

                }
                //实例化交互绘制类对象 并添加到地图容器之中
                draw = new ol.interaction.Draw({
                    //绘制层数据源
                    source: vectorDrawSource,
                    /** @type {ol.geom.GeometryType}**/
                    type: value,
                    //几何信息变更时调用的函数
                    geometryFunction: geometryFunction,
                    maxPoints: maxPoints
                });
                map.addInteraction(draw);
            }


            else {
                vectorDrawSource = null;
                //清空绘制图形
                vectorDrawLayer.setSource(vectorDrawSource);
            }
        }



        /**
         * 添加一个新的图文标注（overlay标注）
         * @param {ol.Coordinate} coordinate 坐标点
         */
        function addOverlayLabel(coordinate) {
            
            var result = prompt("此点的标注信息：");
            var pop = "标注点";
            if(result != null&&result != ""){
                pop = result;
            }
            //新增div元素
            var elementDiv = document.createElement("div");
            elementDiv.className = "marker";
            elementDiv.title = pop;
            //获取id为label的元素
            var overlay = document.getElementById("label");
            //在id为label的的div层添加div子节点
            overlay.appendChild(elementDiv);
            //新增a元素
            var elementA = document.createElement("a");
            elementA.className = "address";
            elementA.href = "#";
            //设置文本
            setInnerText(elementA, elementDiv.title);
            //新建div元素添加子节点a
            elementDiv.appendChild(elementA);

            //实例化图文标注的（图形 + 文本） 添加到地图容器之中
            var newMarker = new ol.Overlay({
                position: coordinate,
                positioning: 'center-center',
                element: elementDiv,

            });
            map.addOverlay(newMarker);
            var newText = new ol.Overlay({
                position: coordinate,
                element: elementA
            });
            map.addOverlay(newText);
        }



        /**
         * 添加矢量标注事件的实现
         * @param{ol.coordinate} coordinate 坐标点
         */
        function addVectorLabel(coordinate) {
            var result = prompt("此点的标注信息：");
            var pop = "标注点";
            if(result != null&&result != ""){
                pop = result;
            }

            //新建一个要素 ol.Feature
            var newFeature = new ol.Feature({
                //几何信息
                geometry: new ol.geom.Point(coordinate),
                //名称属性
                name: pop       //之后让用户自行输入名称属性

            });
            //设置要素的样式
            newFeature.setStyle(createLabelStyle(newFeature));
            //将新要素添加到数据源中
            vectorMarkSource.addFeature(newFeature);
        }





    </script>

</body>

</html>